package com.auto.survey.activity.monitoring.adapter

import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R
import com.auto.survey.activity.monitoring.entity.relations.MonitoringPointWithCtrlObserv
import com.auto.survey.util.Helper

/**
 * 闭合观测序列
 */
class ClosedLoopObserverAdapter : RecyclerView.Adapter<ClosedLoopObserverAdapter.ClosedLoopObserverViewHodler>(){

    private var mItems = mutableListOf<MonitoringPointWithCtrlObserv>()

    fun setItems(items: MutableList<MonitoringPointWithCtrlObserv>) {
        mItems = items
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClosedLoopObserverViewHodler {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.adapter_closed_loop, parent, false)
        return ClosedLoopObserverViewHodler(view)
    }

    override fun onBindViewHolder(holder: ClosedLoopObserverViewHodler, position: Int ) {

        val pointName = mItems[position].point.pointName
        val tempText = when (position) {
            0 -> "（起始）"
            mItems.lastIndex -> "（闭合）"
            else -> ""
        }

        // 组合原始文本
        val fullText = "$pointName$tempText"
        val spannable = SpannableString(fullText)

        // 计算tempText在完整文本中的起始索引
        val tempStartIndex = pointName.length
        val tempEndIndex = fullText.length

        // 给tempText设置较小的字体（例如12sp，根据需求调整）
        if (tempText.isNotEmpty()) {
            spannable.setSpan(
                AbsoluteSizeSpan(14, true), // 第二个参数true表示单位为sp
                tempStartIndex,
                tempEndIndex,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }

        holder.pointName.text = spannable

        when(mItems[position].point.mirrorType) {
            0 -> holder.mirror.text =  "圆棱镜"
            1 -> holder.mirror.text =  "迷你棱镜"
            2 -> holder.mirror.text =  "反射片"
        }

        holder.mirrorHeight.text = "觇标高：${mItems[position].point.mirrorHeight}米"

        holder.mirrorNum.text =  "编号：${mItems[position].point.pointCode}"

        // 获取观测数据
        if (mItems[position].observations.isEmpty()) {
            holder.measureL.text = "左：--.--.--"
            holder.measureR.text = "右：--.--.--"
            holder.measure2C.text="2C:--"
            holder.measure2D.text="2D:--"
        } else {
            val observation = mItems[position].observations[0]

            // 格式化左观测数据
            holder.measureL.text = formatObservationText(
                prefix = "左：",
                horizontalAngle = observation.horizontalAngleL,
                verticalAngle = observation.verticalAngleL,
                distance = observation.distanceL
            )

            // 格式化右观测数据
            holder.measureR.text = formatObservationText(
                prefix = "右：",
                horizontalAngle = observation.horizontalAngleR,
                verticalAngle = observation.verticalAngleR,
                distance = observation.distanceR
            )

            val measure2C = observation.measure2C.takeIf { it != null }
            if (measure2C != null) {
                holder.measure2C.text="2C:$measure2C"
            } else {
                holder.measure2C.text="2C:--"
            }

            val measure2D = observation.measure2D.takeIf { it != null }
            if (measure2D != null) {
                holder.measure2D.text="2D:$measure2D"
            } else {
                holder.measure2D.text="2D:--"
            }

        }
    }

    // 提取的公共格式化函数
    private fun formatObservationText(
        prefix: String,
        horizontalAngle: Double?,
        verticalAngle: Double?,
        distance: Double?
    ): String {
        return buildString {
            append(prefix)

            // 处理水平角
            val horizontalValid = horizontalAngle.takeIf { it != null }
            append(if (horizontalValid != null) {
                "H${Helper.radiansToDMSString(horizontalValid)}"
            } else {
                "--"
            })

            // 处理垂直角：统一用空格分隔，修复原逻辑中"."多余的问题
            val verticalValid = verticalAngle.takeIf { it != null }
            append(if (verticalValid != null) {
                " V${Helper.radiansToDMSString(verticalValid)}"
            } else {
                " --"  // 保持空格对齐
            })

            // 处理距离：仅当水平角和垂直角均有效且距离非null时显示
            val distanceValid = horizontalValid != null && verticalValid != null && distance != null
            append(if (distanceValid) {
                " SD${Helper.formateDecimal(distance)}"
            } else {
                " --"  // 保持空格对齐
            })
        }
    }

    override fun getItemCount(): Int {
        if (mItems.isNotEmpty()) {
            return mItems.size
        }
        return 0
    }


    inner class ClosedLoopObserverViewHodler(itemview: View) : RecyclerView.ViewHolder(itemview){
        val pointName = itemview.findViewById<TextView>(R.id.tv_closedloop_item_poingName)
        val measureL = itemview.findViewById<TextView>(R.id.tv_closedloop_item_left)
        val measureR = itemview.findViewById<TextView>(R.id.tv_closedloop_item_right)
        val mirror = itemview.findViewById<TextView>(R.id.tv_closedloop_item_mirror)
        val mirrorHeight = itemview.findViewById<TextView>(R.id.tv_closedloop_item_mirrorheight)
        val mirrorNum = itemview.findViewById<TextView>(R.id.tv_closedloop_item_mirrornum)
        val measure2C = itemview.findViewById<TextView>(R.id.tv_closedloop_item_2c)
        val measure2D = itemview.findViewById<TextView>(R.id.tv_closedloop_item_2d)
    }
}